﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace PetaPoco
{
    public partial class Sql
    {
        /// <summary>
        /// 根据不同的操作方式，返回对应的格式化值
        /// </summary>
        /// <param name="operateType">操作类型</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        private object GetOperateValueText(OperateType operateType, string value)
        {
            switch (operateType)
            {
                case OperateType.Like:
                    return "%" + value + "%";
                case OperateType.In:
                    return "(" + value + ")";
                default:
                    if (Regex.IsMatch(value, @"^[0-9]+$", RegexOptions.Compiled))
                    {
                        try
                        {
                            return int.Parse(value);
                        }
                        catch (Exception)
                        {

                        }
                        return value;

                    }

                    return value;
            }
        }

        public Sql Where(List<ScriptSearch> scriptSearchs)
        {
            for (int i = 0; i < scriptSearchs.Count; i++)
            {
                var scriptSearch = scriptSearchs[i];

                if (!string.IsNullOrEmpty(scriptSearch.TableName))
                    scriptSearch.Column = scriptSearch.TableName + "." + scriptSearch.Column;

                if (scriptSearch.Column.Contains(' ') || scriptSearch.Column.Contains(';'))
                    continue;

                if (scriptSearch.Operate != OperateType.In)
                    this.Where(scriptSearch.Column + scriptSearch.Operate.GetOperate() + "@0", GetOperateValueText(scriptSearch.Operate, scriptSearch.Value));
                else
                    this.Where(scriptSearch.Column + scriptSearch.Operate.GetOperate() + GetOperateValueText(scriptSearch.Operate, scriptSearch.Value));
            }

            return this;

            //return Append(new Sql("WHERE (" + sql + ")", args));
        }
    }
}
